package sg.edu.nus.comp.qa;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sg.edu.nus.comp.qa.question.ComparableQuestion;
import sg.edu.nus.comp.qa.question.parser.QuestionListParser;
import sg.edu.nus.comp.qa.question.parser.QuestionMapParser;
import sg.edu.nus.comp.qa.utils.WordNetDictionary;

public class QAInitializer {
	private static Log LOGGER = LogFactory.getLog(QAInitializer.class);
	private static String LIST_MAP_SEPERATOR = ", ";
	public static final QAInitializer SINGLETON = new QAInitializer();
	
	private final Map<String, List<Integer>> questionMap = new HashMap<String, List<Integer>>();
	private final List<ComparableQuestion> questionList = new ArrayList<ComparableQuestion>();
	private String dbPathFile;
	private List<String> dbFiles;
	
	private QAInitializer(){
		
	}
	public void init(String dbPathFile) throws Exception{
		dbFiles = new ArrayList<String>();
		this.dbPathFile = dbPathFile;
		readDBPath();
		readQuestions();
		LOGGER.info("Question Database Initialized");
		WordNetDictionary.init();
		LOGGER.info("Successfully Initialized");
	}
	
	private void readQuestions() {
		QuestionListParser listParser = new QuestionListParser();
		QuestionMapParser mapParser = new QuestionMapParser();
		for(String file : dbFiles){
			String[] files = file.split(LIST_MAP_SEPERATOR);
			listParser.loadFile(files[0], questionList);
			mapParser.loadFile(files[1], questionMap);
		}
	}
	private void readDBPath() {
		File file = new File(dbPathFile);
		try {
			Scanner sc = new Scanner(new FileInputStream(file));
			while(sc.hasNext()){
				dbFiles.add(sc.nextLine());
			}
			sc.close();
		} catch (FileNotFoundException e) {
			LOGGER.error("File Not Found", e);
		}
		
	}
	public String getDbPathFile() {
		return dbPathFile;
	}
	public void setDbPathFile(String dbPathFile) {
		this.dbPathFile = dbPathFile;
	}
	public Map<String, List<Integer>> getQuestionMap() {
		return questionMap;
	}
	public List<ComparableQuestion> getQuestionList() {
		return questionList;
	}
}
